package com.axzhengxin.platform.statistics.controller;

import com.axzhengxin.platform.business.domain.BizApplyInfo;
import com.axzhengxin.platform.business.service.IBizApplyInfoService;
import com.axzhengxin.platform.financeProduct.service.IFspFinanceProductService;
import com.axzhengxin.platform.statistics.domain.ProductSearch;
import com.axzhengxin.platform.statistics.domain.ProvinceStatistics;
import com.axzhengxin.platform.statistics.service.ProvinceStatisticsService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author AHZJ0005
 * 统计分析
 */
@RestController
@RequestMapping("/statistics/bizApplyInfo")
public class ProvinceStatisticsController extends BaseController {
    @Autowired
    private IBizApplyInfoService bizApplyInfoService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ProvinceStatisticsService provinceStatisticsService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDictDataService iSysDictDataService;
    @Autowired
    private IFspFinanceProductService fspFinanceProductService;

    /**
     * 获取统计信息
     */
    @PreAuthorize("@ss.hasPermi('statistics:bizApplyInfo:getNumericalStatement')")
    @RequestMapping("/getNumericalStatement")
    public TableDataInfo getNumericalStatement(ProductSearch productSearch, String type) {
        List<ProvinceStatistics> numericalStatementByDept = new ArrayList<ProvinceStatistics>();
        //判断是否是各种管理员
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        Set<String> roles = permissionService.getRolePermission(user);
        int isAdmin = roles.stream().filter(role ->
                "provincial_supervision".equals(role) || "bankvipadmin".equals(role) || "banknrmadmin".equals(role) || "ecsc_sub_1_admin".equals(role) || "ecsc_sub_2_admin".equals(role)
        ).collect(Collectors.toList()).size();
        Long deptId = user.getDeptId();
        productSearch.setDeptId(deptId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (isAdmin > 0 || SecurityUtils.isAdmin(userId)) {
            Integer ancLength = provinceStatisticsService.getAncLength(deptId);
            productSearch.setAncLength(ancLength);
            if (SecurityUtils.isAdmin(userId)){
                productSearch.setIsAdmin(0);
            }else {
                productSearch.setIsAdmin(1);
            }
            startPage();
            if ("1".equals(type)) {
                numericalStatementByDept = provinceStatisticsService.getNumericalStatementByDept(productSearch);
            } else if ("2".equals(type)) {
                if (StringUtils.isEmpty(productSearch.getStartTime())) {
                    productSearch.setStartTime(simpleDateFormat.format(new Date()));
                }
                if (StringUtils.isEmpty(productSearch.getEndTime())) {
                    productSearch.setEndTime(simpleDateFormat.format(new Date()));
                }
                numericalStatementByDept = provinceStatisticsService.getNumericalStatementByDeptYearAndMonth(productSearch);
            } else if ("3".equals(type)) {
                numericalStatementByDept = provinceStatisticsService.getNumericalStatementByArea(productSearch);
            } else if ("4".equals(type)) {
                if (StringUtils.isEmpty(productSearch.getStartTime())) {
                    productSearch.setStartTime(simpleDateFormat.format(new Date()));
                }
                if (StringUtils.isEmpty(productSearch.getEndTime())) {
                    productSearch.setEndTime(simpleDateFormat.format(new Date()));
                }
                numericalStatementByDept = provinceStatisticsService.getNumericalStatementByAreaMonth(productSearch);
            }
            /*if ("1".equals(type) || "2".equals(type)) {
                List<Long> list = new ArrayList<>();
                for (ProvinceStatistics provinceStatistics : numericalStatementByDept) {
                    boolean b = provinceStatistics.getAncestors().endsWith(deptId.toString());
                    if (b) {
                        list.add(provinceStatistics.getDeptId());
                    }
                }
            }*/
        }
        return getDataTable(numericalStatementByDept);
    }

    /**
     * 支行管理员查看的客户经理统计
     */
    @PreAuthorize("@ss.hasPermi('statistics:bizApplyInfo:getNumericalStatementByCustome')")
    @RequestMapping("/getNumericalStatementByCustome")
    public TableDataInfo getNumericalStatementByCustome(ProductSearch productSearch) {
        //必须是支行管理员
        List<ProvinceStatistics> numericalStatementByCustome = new ArrayList<>();
            startPage();
            numericalStatementByCustome = provinceStatisticsService.getNumericalStatementByCustomer(productSearch);
            if (null != numericalStatementByCustome && numericalStatementByCustome.size() > 0) {
                for (ProvinceStatistics provinceStatistics : numericalStatementByCustome) {
                    provinceStatistics.setUserName(provinceStatistics.getNickName() + "(" + provinceStatistics.getUserName() + ")");
                }
            }
        return getDataTable(numericalStatementByCustome);
    }


    public List<Long> getDeptIdList() {
        //查询管理员的下级机构
        List<Long> deptIds = new ArrayList<Long>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Set<String> roles = permissionService.getRolePermission(user);
        int isAdmin = roles.stream().filter(role ->
                "provincial_supervision".equals(role) || "bankvipadmin".equals(role) || "banknrmadmin".equals(role) || "ecsc_sub_1_admin".equals(role) || "ecsc_sub_2_admin".equals(role) || "admin".equals(role)
        ).collect(Collectors.toList()).size();
        if (isAdmin > 0) {
            List<SysDept> depts = deptService.getFirstChildrenDeptById(user.getDeptId());
            if (null != depts && depts.size() > 0) {
                depts.stream().forEach(dept -> {
                    deptIds.add(dept.getDeptId());
                });
            }
        }
        return deptIds;

    }


    /**
     * 产品统计
     *
     * @param productSearch
     * @return
     */
    @PreAuthorize("@ss.hasPermi('statistics:bizApplyInfo:productStatistics')")
    @RequestMapping("/productStatistics")
    public TableDataInfo productStatistics(ProductSearch productSearch) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Set<String> roles = permissionService.getRolePermission(user);
        int provincial = roles.stream().filter(role ->
                "provincial_supervision".equals(role)
        ).collect(Collectors.toList()).size();
        int isBank = roles.stream().filter(role ->
                "bankvipadmin".equals(role) || "banknrmadmin".equals(role) || "ecsc_sub_1_admin".equals(role) || "ecsc_sub_2_admin".equals(role) || "admin".equals(role)
        ).collect(Collectors.toList()).size();
        if (provincial > 0) {
            startPage();
            //省级监管
            if (SecurityUtils.isAdmin(user.getUserId())) {
                productSearch.setIsAdmin(0);
            } else {
                productSearch.setIsAdmin(1);
            }
            return getDataTable(provinceStatisticsService.productStatistics(productSearch));
        } else if (isBank > 0) {
            //金融机构

            productSearch.setDeptId(user.getDeptId());
            productSearch.setAncLength(provinceStatisticsService.getAncLength(user.getDeptId()));
            startPage();
            List<ProvinceStatistics> list = provinceStatisticsService.productStatisticsByDept(productSearch);
            return getDataTable(list);
        } else {
            return getDataTable(new ArrayList<ProvinceStatistics>());
        }
    }

    /**
     * 产品统计  担保方式
     *
     * @param productSearch
     * @return
     */
    @PreAuthorize("@ss.hasPermi('statistics:bizApplyInfo:productStatisticsGuaranteeType')")
    @RequestMapping("/productStatisticsGuaranteeType")
    public TableDataInfo productStatisticsGuaranteeType(ProductSearch productSearch) {
        startPage();
        return getDataTable(provinceStatisticsService.productStatisticsGuaranteeType(productSearch));
    }

    /**
     * 产品统计 单一产品分析
     *
     * @param productSearch
     * @return
     */
    @PreAuthorize("@ss.hasPermi('statistics:bizApplyInfo:productStatisticsByProduct')")
    @RequestMapping("/productStatisticsByProduct")
    public TableDataInfo productStatisticsByProduct(ProductSearch productSearch) {
        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        productSearch.setDeptId(deptId);
        Integer ancLength = provinceStatisticsService.getAncLength(deptId);
        productSearch.setAncLength(ancLength);
        startPage();
        List<ProvinceStatistics> list = provinceStatisticsService.productStatisticsByProduct(productSearch);
        return getDataTable(list);
    }

}
